package com.yuyou.hxyy.service.api.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

/**
 * Created by wens on 2017/7/7.
 */
public class Webs {

    private static SimpleDateFormat sdf = new SimpleDateFormat("-yyyyMMddHHmm");

    public static void writeExcel(HttpServletRequest request, HttpServletResponse response, XSSFWorkbook excel , String fileName )  {
        try{
            fileName = fileName + sdf.format(DateUtil.now());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String browserName=request.getHeader("User-Agent").toLowerCase();
            if (browserName.indexOf("firefox")>0){/*火狐浏览器*/
                response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1")+".xlsx");
            }else{
                response.setHeader("Content-Disposition","attachment;Filename=" + URLEncoder.encode( fileName ,"utf-8") + ".xlsx");
            }
            excel.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();

        }finally {
//            excel.close();
        }

    }

    public static void writeExcel(HttpServletResponse response, HSSFWorkbook excel , String fileName, String browserName ) throws IOException {
        try{
            fileName = fileName + sdf.format(DateUtil.now());
            response.setContentType("application/vnd.ms-excel");
            if (browserName.indexOf("firefox")>0){/*火狐浏览器*/
                response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1")+".xls");
            }else{
                response.setHeader("Content-Disposition","attachment;Filename=" + URLEncoder.encode( fileName ,"utf-8") + ".xls");
            }
            excel.write(response.getOutputStream());
        }finally {
//            excel.close();
        }
    }

}
